package com.mmall.controller.backend;

import com.mmall.common.ServerResponse;
import com.mmall.pojo.Product;
import com.mmall.service.IFileService;
import com.mmall.service.IProductService;
import com.mmall.service.IUserService;
import com.mmall.utils.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/manage/product")
public class ProductManageController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IProductService iProductService;

    @Autowired
    private IFileService iFileService;

    /**
     * 新增或者更新产品
     * @param request
     * @param product
     * @return
     */
    @RequestMapping("save")
    @ResponseBody
    public ServerResponse productSave(HttpServletRequest request, Product product) {
//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
//        }
//        String userJsonStr = RedisPoolUtil.get(loginToken);
//        User user = JsonUtil.stringToObj(userJsonStr, User.class);
//        if (user == null) {
//            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
//        }
//        if (iUserService.checkAdminRole(user).isSuccess()) {
//            //更新categoryName
//            return iProductService.saveOrUpdateProduct(product);
//        } else {
//            return ServerResponse.retErrorMsg("无权限操作,需要管理员权限");
//        }
        //全部通过拦截器验证是否登陆以及权限
        return iProductService.saveOrUpdateProduct(product);
    }

    /**
     * 修改产品销售状态
     * @param request
     * @param productId
     * @param status
     * @return
     */
    @RequestMapping("setSaleStatus")
    @ResponseBody
    public ServerResponse setSaleStatus(HttpServletRequest request, Integer productId, Integer status) {
        //全部通过拦截器验证是否登陆以及权限
        return iProductService.setSaleStatus(productId, status);
    }

    /**
     * 获取产品详情
     * @param request
     * @param productId
     * @return
     */
    @RequestMapping("getDetail")
    @ResponseBody
    public ServerResponse getDetail(HttpServletRequest request, Integer productId) {
        //全部通过拦截器验证是否登陆以及权限
        return iProductService.manageProductDetail(productId);
    }

    /**
     * 查询列表，分页
     * @param request
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("getList")
    @ResponseBody
    public ServerResponse getList(HttpServletRequest request,
                                  @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        //全部通过拦截器验证是否登陆以及权限
        return iProductService.getProductList(pageNum, pageSize);
    }

    /**
     * 产品查询，分页
     * @param request
     * @param productName
     * @param productId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("search")
    @ResponseBody
    public ServerResponse productSearch(HttpServletRequest request,
                                        String productName,
                                        Integer productId,
                                        @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        //全部通过拦截器验证是否登陆以及权限
        return iProductService.searchProduct(productName, productId, pageNum, pageSize);
    }

    /**
     * 文件上传
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("upload")
    @ResponseBody
    public ServerResponse upload(@RequestParam(value = "upload_file", required = false) MultipartFile file,
                                 HttpServletRequest request) {

//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
//        }
//        String userJsonStr = RedisPoolUtil.get(loginToken);
//        User user = JsonUtil.stringToObj(userJsonStr, User.class);
//        if (user == null) {
//            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
//        }
//        if (iUserService.checkAdminRole(user).isSuccess()) {
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file, path);
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix");
            Map fileMap = new HashMap();
            fileMap.put("uri", targetFileName);
            fileMap.put("url", url);
            return ServerResponse.retSuccessData(fileMap);
//        } else {
//            return ServerResponse.retErrorMsg("无权限操作,需要管理员权限");
//        }
    }

    /**
     * 富文本上传
     * @param file
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("richTextImgUpload")
    @ResponseBody
    public Map richTextImgUpload(@RequestParam(value = "upload_file", required = false) MultipartFile file,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {

        Map resultMap = new HashMap();
//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            resultMap.put("success", false);
//            resultMap.put("msg", "用户未登录，无法获取信息");
//            return resultMap;
//        }
//        String userJsonStr = RedisPoolUtil.get(loginToken);
//        User user = JsonUtil.stringToObj(userJsonStr, User.class);
//        if (user == null) {
//            resultMap.put("success", false);
//            resultMap.put("msg", "请登录管理员");
//            return resultMap;
//        }
//        if (iUserService.checkAdminRole(user).isSuccess()) {
            //富文本中对于返回值有要求
            //富文本中对于返回值有自己的要求,我们使用是simditor所以按照simditor的要求进行返回
//        {
//            "success": true/false,
//                "msg": "error message", # optional
//            "file_path": "[real file path]"
//        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file, path);
        if (StringUtils.isBlank(targetFileName)) {
            resultMap.put("success", false);
            resultMap.put("msg", "上传失败");
            return resultMap;
        }
        String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
        resultMap.put("success", true);
        resultMap.put("msg", "上传成功");
        resultMap.put("file_path", url);
        response.addHeader("Access-Control-Allow-Headers", "X-File-Name");
        return resultMap;
//        } else {
//            resultMap.put("success", false);
//            resultMap.put("msg", "无权限操作");
//            return resultMap;
//        }
    }
}
